package org.gkolpu.validation;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;

import org.gkolpu.validation.oval.basetypes.Request;

public class OvalValidator {
	static final Logger log = Logger.getLogger("org.gkolpu.validation");

	{
		log.setLevel(Level.INFO);

	}

	public boolean validate(Request request) {
		Validator validator = new Validator();
		List<String> errorCodes = new ArrayList<String>();
		List<ConstraintViolation> violations = validator.validate(request);

		if (violations.size() > 0) {
			log.info("Object " + request + " is invalid.");
			for (ConstraintViolation constraintViolation : violations) {

				getErrorCodesFromConstraints(errorCodes, constraintViolation);
			}
			log.info(errorCodes.toString());
			return false;
		}
		return true;

	}

	private void getErrorCodesFromConstraints(List<String> errorCodes,
			ConstraintViolation parentConstraintViolation) {
		if (parentConstraintViolation.getCauses() != null) {
			for (ConstraintViolation violation : parentConstraintViolation
					.getCauses()) {
				getErrorCodesFromConstraints(errorCodes, violation);
			}
		} else {
			errorCodes.add(parentConstraintViolation.getErrorCode());
		}
	}
}
